package com.haixee.parkdemo.gateway.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.haixee.parkdemo.common.entity.AuthData;
import com.haixee.parkdemo.gateway.constants.WebConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

/**
 * @author windtreeland
 * 2021/5/10 16:13
 */
@Slf4j
//@Component
public class ServiceFilter implements WebFilter {

//    @Override
//    public GatewayFilter apply(Object config) {
//
//        InnerFilter innerFilter = new InnerFilter();
//        innerFilter.setAuthService(authService);
//
//        return innerFilter;
//    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {

        AuthData data = (AuthData) exchange.getAttributes().get(WebConstants.AUTH_DATA);

        String uidVar = null;
        String authDataVar = null;


        if (data != null) {
            if (data.getUid() != null) {
                uidVar = data.getUid().toString();
                exchange.getAttributes().put(WebConstants.HEADER_UID, uidVar);
            }


            ObjectMapper objectMapper = new ObjectMapper();
            try {
                authDataVar = objectMapper.writeValueAsString(data);
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        }

        // 将uid放在请求头给微服务提供权限信息
        ServerHttpRequest request = exchange.getRequest().mutate()
                .header(WebConstants.HEADER_UID, uidVar)
                .header(WebConstants.AUTH_DATA, authDataVar)
                .build();
        return chain.filter(exchange.mutate().request(request).build());
    }
}
